/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Factory.DAO.MySQL;

import DatabaseConnection.DBConnectionFactory;
import Factory.DAO.LogDAO;
import Factory.DAOFactory;
import Factory.Tables.Log;
import Factory.Tables.LogDef;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Patrick
 */
public class MySQLLogDAO extends LogDAO{

    @Override
    public void addLog(Log obj) {
        try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            try (Connection conn = myFactory.getConnection()) {
                PreparedStatement pstmt = conn.prepareStatement("insert into log(datelog,timelog,iduser,idlogdef) values (?,?,?,?) ");
                pstmt.setDate(1, obj.getLogDate());
                pstmt.setTime(2, obj.getLogTime());
                pstmt.setInt(3, obj.getUserID());
                pstmt.setInt(4, obj.getLogDefID());
                pstmt.executeUpdate();
            }
        } catch (SQLException ex) {
            Logger.getLogger(MySQLLogDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public List<Log> getLogByUserID(int userID) {
        try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            try (Connection conn = myFactory.getConnection()) {
                PreparedStatement pstmt = conn.prepareStatement("select * from log natural join logdef where iduser = ? order by datelog desc, timelog desc");
                pstmt.setInt(1, userID);
                ResultSet rs = pstmt.executeQuery();
                ArrayList<Log> result = new ArrayList<>();
                Log log;
                LogDef logDef;
                while(rs.next()){
                    log = new Log();
                    logDef = new LogDef();
                    log.setLogDefID(rs.getInt("idlog"));
                    log.setUserID(userID);
                    log.setLogDate(rs.getDate("datelog"));
                    log.setLogTime(rs.getTime("timelog"));
                    log.setLogDefID(rs.getInt("idlogdef"));
                    logDef.setLogDefID(rs.getInt("idlogdef"));
                    logDef.setLogDefName(rs.getString("logdefname"));
                    result.add(log);
                }
                conn.close();
                return result;
            }
        } catch (SQLException ex) {
            Logger.getLogger(MySQLLogDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
}
